package cn.com.platform.web.manage.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.controller.BaseController;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.platform.dao.ArticleCateDao;
import cn.com.platform.dao.ArticleDao;
import cn.com.platform.entity.ArticleCateEntity;
import cn.com.platform.entity.ArticleEntity;

import com.google.common.collect.Lists;

/**
 * 文章分类管理
 * 
 * @author wxy 2016年8月3日
 */
@Controller
@RequestMapping("/manage/article/cate")
public class ArticleCateManageController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(ArticleCateManageController.class);

	/**
	 * 文章分类dao
	 */
	@Autowired
	private ArticleCateDao articleCateDao;

	/**
	 * 文章dao
	 */
	@Autowired
	private ArticleDao articleDao;

	/**
	 * 文章分类管理
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("文章分类管理")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/manage/article/article_cate/article_cate";
	}

	/**
	 * 获取所有文章分类
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("获取所有文章分类")
	@RequestMapping("/get/all")
	public void getAllCate(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {
			pageRequestParamDTO.setPageSize(10000);
			if (StringUtils.isBlank(pageRequestParamDTO.getSortName()) == true) {
				pageRequestParamDTO.setSortName("orderby");
				pageRequestParamDTO.setSortOrder("asc");
			}
			org.springframework.data.domain.Page<ArticleCateEntity> page = articleCateDao.findByDeleteStatus(pageRequestParamDTO.buildSpringDataPageRequest(), false);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, PageUtils.getPage(page)));

		} catch (Exception ex) {
			logger.error("获取所有文章分类异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有文章分类异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 添加或更新文章分类
	 * 
	 * @param request
	 * @param response
	 * @param file
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("添加或更新文章分类")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void addCate(HttpServletRequest request, HttpServletResponse response, ArticleCateEntity articleCateEntity) {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if(StringUtils.isEmpty(articleCateEntity.getTitle())){
				throw new BusinessException("分类标题不能为空");
			}
			if(StringUtils.isEmpty(articleCateEntity.getPinyin())){
				throw new BusinessException("字母全拼小写不能为空");
			}
			// 层级
			if (articleCateEntity.getParentId() != null) {
				ArticleCateEntity temp = articleCateDao.findOne(articleCateEntity.getParentId());
				if (temp != null) {
					articleCateEntity.setLevel(temp.getLevel() + 1);
				}
			}
			if (articleCateEntity.getId() == null) {
				articleCateEntity.setCreateBy(user.getLoginname());
				articleCateDao.save(articleCateEntity);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, articleCateEntity));
			} else {

				// 更新
				ArticleCateEntity articleCateEntityTemp = articleCateDao.findOne(articleCateEntity.getId());
				if (articleCateEntityTemp == null) {
					throw new BusinessException("未找到分类！");
				} else {
					articleCateEntityTemp.setLastModifyBy(this.getCurrentUser(request).getLoginname());

					articleCateEntityTemp.setTitle(articleCateEntity.getTitle());
					articleCateEntityTemp.setPinyin(articleCateEntity.getPinyin());
					articleCateEntityTemp.setSeoTitle(articleCateEntity.getSeoTitle());
					articleCateEntityTemp.setSeoKeywords(articleCateEntity.getSeoKeywords());
					articleCateEntityTemp.setSeoDescription(articleCateEntity.getSeoDescription());
					articleCateEntityTemp.setHidden(articleCateEntity.getHidden());
					articleCateEntityTemp.setOrderby(articleCateEntity.getOrderby());
					
					articleCateEntityTemp.setLastModifyBy(user.getLoginname());
					articleCateEntityTemp.setLastModifyTime(new Date());
					articleCateDao.save(articleCateEntityTemp);
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, articleCateEntityTemp));
				}
			}
		} catch (Exception ex) {
			logger.error("添加或更新添加或更新文章分类异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "添加或更新文章分类异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除文章分类
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("删除文章分类")
	@RequestMapping(value = "/delete")
	public void deleteCate(HttpServletRequest request, HttpServletResponse response, ArticleCateEntity articleCateEntity) {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			// 子节点数量
			Integer count = articleCateDao.countByParentId(articleCateEntity.getId(), false);
			if (count != null && count > 0) {
				throw new BusinessException("文章分类节点下存在其他子分类，不能直接删除！");
			} else {
				ArticleCateEntity articleCateEntityTemp = articleCateDao.findByIdAndTitle(articleCateEntity.getId(), articleCateEntity.getTitle());
				if (articleCateEntityTemp != null) {
					// 有关联到文章不能删除
					List<ArticleEntity> list = articleDao.findArticleListByCateId(articleCateEntity.getId(), false);

					if (CollectionUtils.isNotEmpty(list)) {
						List<String> titles = Lists.newArrayList();
						for (ArticleEntity temp : list) {
							titles.add(temp.getTitle());
						}
						throw new BusinessException("当前文章分类关联到其他文章，不能直接删除！<br/>文章：" + StringUtils.join(titles, "，"));
					}
					articleCateEntityTemp.setDeleteStatus(true);
					articleCateEntityTemp.setLastModifyBy(user.getLoginname());
					articleCateEntityTemp.setLastModifyTime(new Date());
					articleCateDao.save(articleCateEntityTemp);
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
				} else {
					throw new BusinessException("未找到该文章分类");
				}
			}
		} catch (Exception ex) {
			logger.error("删除文章分类异常，id:" + articleCateEntity.getId(), ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除文章分类异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 移动分类
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("移动文章分类")
	@RequestMapping(value = "/move")
	public void moveCate(HttpServletRequest request, HttpServletResponse response, Long id, Long parentId) {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}

			if (parentId == null) {
				throw new BusinessException("父节点id不能为空！");
			} else {
				ArticleCateEntity articleEntity = articleCateDao.findOne(id);
				if (articleEntity != null) {
					if (parentId.longValue() == articleEntity.getId()) {
						throw new BusinessException("不能选择自身节点作为父节点！");
					}
					if (articleEntity.getParentId()!=null && parentId.longValue() == articleEntity.getParentId()) {
						// 父节点已经是本身的父節點
						ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
						return;
					}
					articleEntity.setParentId(parentId);
					articleEntity.setLastModifyBy(user.getLoginname());
					articleEntity.setLastModifyTime(new Date());
					articleCateDao.save(articleEntity);
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
					return;
				} else {
					throw new BusinessException("未找到文章分类");
				}
			}
		} catch (Exception ex) {
			logger.error("移动文章分类异常，id:" + id, ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "移动文章分类异常.ex:" + ex.getLocalizedMessage()));
		}
	}

}
